package com.example.courseapp.activity;

import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.courseapp.R;
import com.example.courseapp.RetrofitHelper;
import com.example.courseapp.SharedPreferencesHelper;
import com.example.courseapp.bean.AddChildInfo;
import com.example.courseapp.bean.ChildInformation;
import com.example.courseapp.net.CourseService;

import java.util.Calendar;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class AddChildActivity extends AppCompatActivity {
    EditText name, height, weight;

    TextView sex,birthdate ,age;
    ImageView btn_sex;
    ImageView btn_birth;


    private int flag=0;
    private int choice=0;
    Button commit;



    ChildInformation childInformation;

    CourseService courseService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_add_child);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        childInformation = (ChildInformation) getIntent().getSerializableExtra("childInfo");

        courseService = RetrofitHelper.getInstance().createService(CourseService.class);

        name = findViewById(R.id.name);
        age = findViewById(R.id.age);
        height = findViewById(R.id.height);
        weight = findViewById(R.id.weight);

        sex = findViewById(R.id.sex);
        btn_sex = findViewById(R.id.btn_sex);
        btn_birth =  findViewById(R.id.btn_birth);
        birthdate =findViewById(R.id.birthdate);

        commit = findViewById(R.id.commit);

        commit.setOnClickListener(v -> {
            commitFun();
        });

        findViewById(R.id.back).setOnClickListener(v -> {
            finish();
        });

        if (childInformation != null) {
            if (childInformation.getBirthdate() != null) {
                birthdate.setText(childInformation.getBirthdate());
            }
            name.setText(childInformation.getChildName());
            age.setText(childInformation.getAge()+"");
            height.setText(childInformation.getHeight() + "");
            weight.setText(childInformation.getWeight() + "");
            sex.setText(childInformation.getSex() + "");
        }
        //性别选择

        btn_sex.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String arr[] ={"男","女"};
                AlertDialog.Builder b=new AlertDialog.Builder(AddChildActivity.this);
                b.setTitle("选择性别");
                b.setSingleChoiceItems(arr, 0, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        sex.setText(arr[which]);
                        //String sex = sex.getText().toString();
                        dialog.dismiss();
                    }
                });
                b.show();
            }
        });
        //出生日期选择
        btn_birth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //控制器显示获取当前日期
                Calendar c= Calendar.getInstance();
                int nowYear=c.get(Calendar.YEAR);
                int nowMonth=c.get(Calendar.MONTH);
                int nowDay=c.get(Calendar.DAY_OF_MONTH);


                DatePickerDialog d=new DatePickerDialog(AddChildActivity.this,new DatePickerDialog.OnDateSetListener(){

                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        //tv_birthday.setText(year + "年" + (month + 1) + "月" + dayOfMonth + "日");
                        birthdate.setText(year + "-" + (month + 1) + "-" + dayOfMonth);
                        //计算年龄
                        int aage = nowYear - year;
                        if (nowMonth < month || (nowMonth == month && nowDay < dayOfMonth)){
                            aage--;
                        }
                      String a = String.format("%d", aage);
                        age.setText(a);


                    }

                },nowYear,nowMonth,nowDay);
                d.show();

            }

        });
    }


    public void commitFun() {
        String nameStr = name.getText().toString();
        String ageStr = age.getText().toString();
        String heightStr = height.getText().toString();
        String weightStr = weight.getText().toString();
        String sexStr = sex.getText().toString();
        String birthdateStr = birthdate.getText().toString();

        if (childInformation != null) {
            childInformation.setChildName(nameStr);
            childInformation.setAge(Integer.valueOf(ageStr));
            childInformation.setHeight(Float.valueOf(heightStr));
            childInformation.setWeight(Float.valueOf(weightStr));
            childInformation.setSex(sexStr);
            childInformation.updateBmi();
            childInformation.setBirthdate(birthdateStr);
            courseService.changeChildInfo(childInformation).enqueue(callback);
        } else {
            ChildInformation childInformation = new ChildInformation();
            childInformation.setChildName(nameStr);
            childInformation.setAge(Integer.parseInt(ageStr));
            childInformation.setHeight(Float.parseFloat(heightStr));
            childInformation.setWeight(Float.parseFloat(weightStr));
            childInformation.updateBmi();
            childInformation.setSex(sexStr);
            childInformation.setBirthdate(birthdateStr);
            Integer userID = Integer.valueOf(SharedPreferencesHelper.getName(this, "userID"));
            AddChildInfo addChildInfo = new AddChildInfo();
            addChildInfo.setChildInformation(childInformation);
            addChildInfo.setUserID(userID);
            courseService.addChild(addChildInfo).enqueue(callback);
        }
    }


    Callback callback = new Callback<Boolean>() {
        @Override
        public void onResponse(Call<Boolean> call, Response<Boolean> response) {
            if (Boolean.TRUE.equals(response.body())) {
                runOnUiThread(() -> {
                    Toast.makeText(AddChildActivity.this, childInformation != null ? "修改成功" : "添加成功", Toast.LENGTH_SHORT).show();
                    finish();
                });
            }
        }

        @Override
        public void onFailure(Call<Boolean> call, Throwable t) {
            Toast.makeText(AddChildActivity.this, childInformation != null ? "修改失败" : "添加失败", Toast.LENGTH_SHORT).show();

        }
    };
}